package com.zpark.drug.controller;

import com.zpark.drug.pojo.User;
import com.zpark.drug.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping(value = "/login")
    public String login() {
        return "/login";
    }

    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object> login(@RequestParam("username") String username,
                                     @RequestParam("password") String password,
                                     @RequestParam("captcha") String captchaCode,
                                     HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        // 获取session中的验证码
        String sessionCaptcha = (String) session.getAttribute("captcha");
        if (!captchaCode.equalsIgnoreCase(sessionCaptcha)) {
            result.put("code", "0");
            result.put("msg", "验证码错误，请重新输入");
            result.put("icon", 2);
            result.put("anim", 6);
            return result;
        }

        // 进行用户登录验证
        User user = userService.login(username, password);
        if (user != null) {
            session.setAttribute("user", user);
            result.put("code", "1");
            result.put("msg", "登录成功");
            result.put("icon", 1);
            result.put("anim", 1);
        } else {
            result.put("code", "0");
            result.put("msg", "用户名或密码错误");
            result.put("icon", 2);
            result.put("anim", 6);
        }
        return result;
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "/login";
    }

    @RequestMapping(value = "/register")
    public String register() {
        return "/register";
    }

    @PostMapping("/register")
    @ResponseBody
    public Map<String, Object> register(@RequestParam("username") String username,
                                        @RequestParam("password") String password,
                                        @RequestParam("confirm_password") String confirmPassword,
                                        @RequestParam("user_role") String userRole,
                                        @RequestParam("user_number") String userNumber,
                                        @RequestParam("user_email") String userEmail) {
        Map<String, Object> result = new HashMap<>();

        // 检查两次密码是否一致
        if (!password.equals(confirmPassword)) {
            result.put("code", "0");
            result.put("msg", "两次密码输入不一致");
            result.put("icon", 2);
            result.put("anim", 6);
            return result;
        }

        // 创建新用户
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        newUser.setRole(userRole);
        newUser.setNumber(userNumber);
        newUser.setEmail(userEmail);

        // 保存用户
        boolean isSaved = userService.saveUser(newUser);
        if (isSaved) {
            result.put("code", "1");
            result.put("msg", "注册成功");
            result.put("icon", 1);
            result.put("anim", 1);
        } else {
            result.put("code", "0");
            result.put("msg", "注册失败，请重试");
            result.put("icon", 2);
            result.put("anim", 6);
        }
        return result;
    }

    @RequestMapping(value = "/forgotPassword")
    public String resetPassword() {
        return "/forgot_password";
    }

    @PostMapping("/resetPassword")
    @ResponseBody
    public Map<String, Object> resetPassword(@RequestParam("email") String email,
                                             @RequestParam("code") String code,
                                             @RequestParam("newPassword") String newPassword,
                                             @RequestParam("confirmPassword") String confirmPassword) {
        Map<String, Object> result = new HashMap<>();

        // 验证验证码
        String emailKey = "email_code_" + email;
        String storedCode = redisTemplate.opsForValue().get(emailKey);

        if (storedCode == null || !storedCode.equals(code)) {
            result.put("code", "0");
            result.put("msg", "验证码错误或已过期");
            result.put("icon", 2);
            result.put("anim", 6);
            return result;
        }

        // 检查两次密码是否一致
        if (!newPassword.equals(confirmPassword)) {
            result.put("code", "0");
            result.put("msg", "两次密码输入不一致");
            result.put("icon", 2);
            result.put("anim", 6);
            return result;
        }

        // 查找用户
        User user = userService.findByEmail(email);
        if (user == null) {
            result.put("code", "0");
            result.put("msg", "用户不存在");
            result.put("icon", 2);
            result.put("anim", 6);
            return result;
        }

        // 更新密码
        boolean isUpdated = userService.updateUserPassword(user.getId(), newPassword);
        if (isUpdated) {
            // 移除已使用的验证码
            redisTemplate.delete(emailKey);
            result.put("code", "1");
            result.put("msg", "密码重置成功");
            result.put("icon", 1);
            result.put("anim", 1);
        } else {
            result.put("code", "0");
            result.put("msg", "密码重置失败，请重试");
            result.put("icon", 2);
            result.put("anim", 6);
        }
        return result;
    }

    @GetMapping("/deleteAccount")
    public String deleteAccount(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user != null) {
            userService.deleteUser(user.getId());
            session.invalidate();
        }
        return "login"; // Redirect to login page after account deletion
    }

    @GetMapping("/profile")
    public String userProfile() {
        return "user-setting"; // Ensure this matches the name of your HTML file without the extension
    }

}
